package com.liam.chinesevietnamesecorpus.common;

import jakarta.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.ModelAttribute;

/**
 * 基础控制器类
 * 提供控制器层的通用功能
 * 
 * @author Liam
 */
public abstract class BaseController {

    /**
     * 当前请求对象
     */
    protected HttpServletRequest request;

    /**
     * 注入request对象
     */
    @ModelAttribute
    public void setRequest(HttpServletRequest request) {
        this.request = request;
    }

    /**
     * 获取客户端IP地址
     */
    protected String getClientIp() {
        String ip = request.getHeader("X-Forwarded-For");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        // 处理多级代理的情况
        if (ip != null && ip.contains(",")) {
            ip = ip.split(",")[0].trim();
        }
        return ip;
    }

    /**
     * 获取User-Agent
     */
    protected String getUserAgent() {
        return request.getHeader("User-Agent");
    }
}
